<template>
  <t-dialog
    header="录入申请付款信息"
    :width="width ? width : '50%'"
    :visible="showDialog"
    @confirm="handleConfirm"
    @close="handleCancel"
    @cancel="handleCancel"
    confirmBtn="申请付款"
    preventScrollThrough
    placement="center"
  >
    <t-form :data="pageData.formData">
      <t-form-item label="信用险额度" name="creditIds" requiredMark :labelWidth="120">
        <InputSelect :value="pageData.creditNames" @onClick="handleCreditShow" />
        <t-button theme="danger" style="margin-left: 6px" @click="handleCreditClear">清除选择</t-button>
      </t-form-item>
      <t-form-item
        label="美元汇率"
        name="exchangeRate"
        requiredMark
        :labelWidth="120"
        :help="`【${exchange.lastDate} 数据】美元汇率：${pageData.usdData?.price}`"
      >
        <t-input-number
          :min="0"
          v-model="pageData.formData.exchangeRate"
          theme="column"
          :decimalPlaces="2"
          style="width: 100%"
        />
      </t-form-item>
    </t-form>
  </t-dialog>

  <SelectTable
    v-if="pageData.credit.show"
    :loading="pageData.credit.loading"
    :title="`选择当前订单客户 ${props.row.customer?.customerNo} 下的信用险额度`"
    :showDialog="pageData.credit.show"
    width="60vw"
    tableMaxHeight="50vh"
    rowSelectionType="multiple"
    :zIndex="2600"
    :selectedRowKeys="pageData.formData.creditIds"
    :tableData="pageData.credit.data"
    :columns="creditColumns"
    @onConfirm="handleCreditConfirm"
    @onCancel="handleCreditClose"
    @currentChange="handleCreditSelectChange"
  />
</template>

<script lang="tsx" setup>
// 框架和组件库
import { reactive, toRaw } from "vue";

// 工具函数
import { http } from "@/utils/fetch";
// import { newPrecision } from "@/utils/tools";

// API
import { getCreditList } from "@/api/merchants";

// 业务数据
import { creditColumns } from "@/pages/Dashboard/Merchants/Customer/components/columns";
import { MessagePlugin } from "tdesign-vue-next";

const props = defineProps(["id", "width", "showDialog", "exchange", "row"]);
const emits = defineEmits(["onClose"]);

const CREATE_FORM_PATH = "/billing/create"; // 创建接口

const pageData = reactive({
  creditNames: "",
  formData: {
    id: "",
    status: 0,
    hasDeleted: 0,
    remark: "",
    orderId: props.id,
    creditIds: [],
    exchangeRate: 0
  },
  usdData: {} as Record<string, any>,
  credit: {
    show: false,
    data: [],
    loading: false,
    columns: []
  }
});

const processExchangeData = () => {
  const usdData = props.exchange.exchangeRate.find((item: Record<string, any>) => item.foreignCName === "USD");
  pageData.usdData = usdData;
};

const getCreditData = async () => {
  pageData.credit.loading = true;
  const resultData = await getCreditList(props.row.orderCustomerId);
  if (resultData.code === 200) {
    pageData.credit.data = resultData.data.map((item: Record<string, any>) => {
      return {
        ...item,
        funderGlobalMainPartName: item.funderGlobalMainPart.customerName,
        funderName: item.funder.companyName
      };
    });
    pageData.credit.loading = false;
  }
};

const handleCreditShow = () => {
  pageData.credit.show = true;
  getCreditData();
};

const handleCreditClose = () => {
  pageData.credit.show = false;
};

const handleCreditConfirm = () => {
  handleCreditClose();
};

const handleCreditClear = () => {
  pageData.formData.creditIds = [];
  pageData.creditNames = "";
};

const handleCreditSelectChange = (e: Record<string, any>) => {
  pageData.formData.creditIds = e.keys;

  // 设置这个函数的目的是为了及时更新数据，免得被误判为“属于已经选中过数据，但是点击选择列表之后没有做出改动”的情况。
  if (e.keys.length === 0) {
    pageData.creditNames = "";
  } else {
    pageData.creditNames = `已选中 “${e.options.selectedRowData[0].funderName}”等 ${e.keys.length} 个`;
  }
};

const handleCancel = () => {
  emits("onClose", "cancel");
};

const handleConfirm = async () => {
  const postFormData = toRaw(pageData.formData);
  const resultData = await http("POST", CREATE_FORM_PATH, postFormData);
  // 根据接口返回结果，提示操作成功或失败，并关闭对话框
  if (resultData.code === 200) {
    MessagePlugin.success("申请成功！");
    emits("onClose", "success");
  }
};

processExchangeData();
</script>
